/*
 * BrowserHiddenFS.java
 *
 * Created on 24.06.2008, 9:19
 *
 * Copyright (c) 2006-2008, Daniel Apatin (ad), http://apatin.net.ru
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * You can also redistribute and/or modify this program under the
 * terms of the Psi License, specified in the accompanied COPYING
 * file, as published by the Psi Project; either dated January 1st,
 * 2005, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package io.file.browse;

import images.RosterIcons;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.List;
import locale.SR;
import midlet.StaticData;
import ui.IconTextElement;
import ui.MainBar;
import ui.VirtualElement;
import ui.VirtualList;

/**
 *
 * @author ad
 */
public class BrowserHiddenFS extends VirtualList {
 
    private Vector dir;
    
    private String currPath="";
    private BrowserListener browserListener;

    private boolean getDirectory;
    
    Hashtable hiddenFS=StaticData.getInstance().hiddenFS;
    //public String b="";
    
    /** Creates a new instance of BrowserHiddenFS */
    public BrowserHiddenFS(String path, Display display, BrowserListener browserListener, boolean getDirectory) {
        super(display);
        
        this.browserListener=browserListener;
	this.getDirectory=getDirectory;
        currPath=path;
		
        setMainBarItem(new MainBar(2, null, null));
        
        // test for empty path
        if (currPath==null) currPath="";
       
        // trim filename
        int l=currPath.lastIndexOf('/');
        if (l<0) {
            currPath=""; 
        } else {
            currPath=currPath.substring(0,l+1);
        }

        fillList();
    }
    
    protected int getItemCount() { return dir.size(); }
    
    protected VirtualElement getItemRef(int index) { return (VirtualElement) dir.elementAt(index); }
    
    private void fillList() {
        getMainBarItem().setElementAt((currPath.endsWith("/"))?currPath.substring(0, currPath.length()-1):currPath,0);//"("+getItemCount()+") "+path, 0);
        dir=new Vector();

        Hashtable hashtable = new Hashtable();
        Enumeration enumeration = hiddenFS.keys();
        Vector dirsVector = new Vector();
        Vector filesVector = new Vector();
        do {
            if(!enumeration.hasMoreElements())
                break;
            String s;
            if((s = "" + enumeration.nextElement()).startsWith(currPath)) {
                if(s.equals(currPath)) {
                    Vector vector2 = (Vector)hiddenFS.get(s);
                    for(int j1 = 0; j1 < vector2.size(); j1++) {
                        String s1;
                        if(!(s1 = "" + vector2.elementAt(j1)).endsWith("/"))
                            filesVector.addElement(s1);
                    }
                }
                if(!(s = getStart(s = s.substring(currPath.length()))).equals("") && hashtable.get(s) == null) {
                    hashtable.put(s, new Integer(0));
                    dirsVector.addElement(s);
                }
            }
        } while(true);

        String dirsArray[] = new String[dirsVector.size()];
        for(int i1 = 0; i1 < dirsArray.length; i1++) {
            dirsArray[i1] = "" + dirsVector.elementAt(i1);
        }
        if(dirsArray.length > 0)
            checkItem(dirsArray, 0, dirsArray.length - 1);
        
        String filesArray[] = new String[filesVector.size()];
        for(int k1 = 0; k1 < filesArray.length; k1++)
            filesArray[k1] = "" + filesVector.elementAt(k1);

        if(filesArray.length > 0)
            checkItem(filesArray, 0, filesArray.length - 1);
        
        
        
        if (currPath!=null)
            if (currPath.length()>0)
                dir.addElement(new FileItem("../"));
        
        for(int l1 = 0; l1 < dirsArray.length; l1++) {
            dir.addElement(new FileItem(dirsArray[l1]));
        }

        for(int i2 = 0; i2 < filesArray.length; i2++) {
            dir.addElement(new FileItem(filesArray[i2]));
        }
        moveCursorHome();
    }
	
    public static String getStart(String src) {
        String str=src.trim();
        int pos=str.indexOf('/');
        if(pos>-1)
            str = str.substring(0, pos + 1);
        return str;
    }
	
    public static void checkItem(String array[], int i1, int j1) {
        int k1 = i1;
        int l1 = j1;
        do {
            String str;
            for(str = array[(k1 + l1) / 2]; array[k1].compareTo(str) < 0; k1++);
                for(; array[l1].compareTo(str) > 0; l1--);
                    if(k1 <= l1) {
                        String s1 = array[k1];
                        array[k1] = array[l1];
                        array[l1] = s1;
                        k1++;
                        l1--;
                    }
        } while(k1 < l1);
        if(l1 > i1)
            checkItem(array, i1, l1);
        if(k1 < j1)
            checkItem(array, k1, j1);
    }
    
    
    public void eventOk() {
        String newPath=((FileItem)getFocusedObject()).name;
        if (!newPath.endsWith("/")) {
            if (browserListener==null) 
                return;
            destroyView();
            browserListener.BrowserFilePathNotify(currPath+newPath);
            return;
        }
        
        if(newPath != null) {
            String s;
            if((s = newPath).equals("../")) {
                goBack();
            } else if(s.endsWith("/")) {
                currPath += s;
                fillList();
                redraw();
            }
        }
    }
    
    private void goBack() {
        if(!currPath.equals("")) {
            String s = currPath.substring(0, currPath.length() - 1);
            currPath = s.substring(0, s.lastIndexOf('/') + 1);
            fillList();
            redraw();
        }
    }
    
    public String getRightCommand() { return SR.MS_BACK; }
    public void rightCommand() { if (currPath.equals("")) destroyView(); else goBack(); }

    private class FileItem extends IconTextElement {
        
        public String name;
        private int iconIndex;
        private int type;
        
        public FileItem(String name) {
            super(RosterIcons.getInstance());
            this.name=name;
            iconIndex=name.endsWith("/")?0x10:0x12;;
        }
        
        public int getImageIndex() { 
            return iconIndex; 
        }
        
        public String toString() { return (name.endsWith("/"))?name.substring(0, name.length()-1):name; }
        
        public int compare(IconTextElement right){
            FileItem fileItem=(FileItem) right;
            
            int cpi=iconIndex-fileItem.iconIndex;
            if (cpi==0) cpi=name.compareTo(fileItem.name);
            return cpi;
        }
        
        public int getType() {
            return type;
        }
    }
}
